package client.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import client.constants.core.ILogConstants;
import client.core.controller.ChatController;
import client.output.Log;

public class ChatClient implements Runnable {

	public static final String SERVER_HOSTNAME = "16.162.8.36";
	public static final int SERVER_PORT = 4096;

	private String username;
	
	private ChatController controller;
	private Sender sender;

	public ChatClient(ChatController controller, String username) {
		this.controller = controller;
		this.username = username;
		
		new Thread(this).start();
	}

	@Override
	public void run() {
		Socket socket = null;

		BufferedReader inputReader = null;
		PrintWriter writer = null;

		try {
			socket = new Socket(SERVER_HOSTNAME, SERVER_PORT);
			inputReader = new BufferedReader(new InputStreamReader(socket
					.getInputStream()));
			writer = new PrintWriter(new OutputStreamWriter(socket
					.getOutputStream()));
			Log.writeLn(ILogConstants.CONNECTED, SERVER_HOSTNAME, SERVER_PORT);
		} catch (IOException ex) {
			Log.writeLn(ILogConstants.CONNECTION_FAILED, SERVER_HOSTNAME,
					SERVER_PORT);
		}

		if (socket != null) {
			sender = new Sender(writer);
			sender.setDaemon(true);
			sender.start();

			try {
				String message;

				while ((message = inputReader.readLine()) != null) {
					this.controller.writeMessage(message);
					// Log.write(message);
				}
			} catch (IOException ex) {
				Log.writeLn(ILogConstants.CONNECTION_BROKEN);
				ex.printStackTrace();
			}
		}
	}

	public void sendMessage(String message) {
		sender.sendMessage(username + ": " + message);
	}
}
